package compro.admission.form.dao;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import compro.admission.form.entity.User;

@Component
@Transactional(propagation = Propagation.MANDATORY)
public class UserDAO {
	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	@Resource
	@Transactional(propagation = Propagation.SUPPORTS)
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}


	public void saveUser(User user) {
		sessionFactory.getCurrentSession().persist(user);
	}

	@Transactional
	public void updateUser(User user) {
		sessionFactory.getCurrentSession().update(user);
	}
	
	public User getUserByEmail(String email) {
		@SuppressWarnings("unchecked")
		List<User> userList  = sessionFactory.getCurrentSession().createQuery("from User where email = :email")
				.setParameter("email", email)
				.list();
		
		if(userList.size() == 0) {
			return null;
		} else {
			return userList.get(0);
		}
	}

	public User getUserByApplicationID(long app_id) {
		@SuppressWarnings("unchecked")
		List<User> userList = sessionFactory.getCurrentSession()
				.createQuery("from User where app_id = :app_id")
				.setParameter("app_id", app_id).list();

		if (userList.size() == 0) {
			return null;
		} else {
			return userList.get(0);
		}
	}

	public User getUserAdmission() {
		@SuppressWarnings("unchecked")
		List<User> userList = sessionFactory.getCurrentSession()
				.createQuery("from User where role = :role")
				.setParameter("role", "admission").list();

		if (userList.size() == 0) {
			return null;
		} else {
			return userList.get(0);
		}
	}
}
